<template>
  <div id="carform">
    <div class="top-area">
      <van-button v-if="tempOperate == 'new'" class="top-button" type="info" plain @click="showPopUpLink">{{ form.workid != 0 ? '重新关联用车审批流程' : '+ 关联用车审批流程' }} </van-button>
    </div>
    
    <van-cell-group>
      <van-cell  class="wrap-cell" v-if="form.workid != 0" title="流程名称">
        <template #default v-if="tempOperate == 'new'">
          <span class="active" @click="cancelLink">取消关联</span>
        </template>
      </van-cell>
      <van-field v-if="form.workid != 0" class="input-field" :value="form.title" disabled></van-field>

      <van-cell title="用车人" class="required" :value="form.user_car || '请选择'" @click="showPicker('user_car', 'user_car', -1)" is-link/>
      <van-cell class="required" @click="showPicker('date', 'arrange_start', -1)" title="开始时间" :value="form.arrange_start ? $common.convertDate(form.arrange_start) : '请选择'" label="" is-link/>
      <van-cell class="required" @click="showPicker('date', 'arrange_end', -1)" title="结束时间" :value="form.arrange_end ? $common.convertDate(form.arrange_end) : '请选择'" label="" is-link/>

      <van-cell class="wrap-cell required" title="目的地">
      </van-cell>
      <van-field class="input-field" :disabled="tempOperate == 'cancel'" v-model="form.destination" placeholder="请输入目的地"></van-field>

      <van-cell title="预计行程 (km)">
        <van-field class="input-field-inline" :disabled="tempOperate == 'cancel'" v-model="form.ex_km" placeholder="请输入里程数"></van-field>
      </van-cell>

      <van-cell class="wrap-cell" title="同行人"/>
      <van-field v-if="(form.peer && form.peer.length == 0) && tempOperate != 'new'" class="input-field" :disabled="true" value="当前暂无同行人"></van-field>
      <van-row class="peoples" :gutter="11">
        <van-col span="4" v-for="(item, index) in form.peer" :key="`${index}同行人`">
          <div class="people-with-name">
            <van-image :src="$common.returnImg(item.pic)"></van-image>
            <p class="van-ellipsis">{{ item.name }}</p>
          </div>
        </van-col>
        <van-col v-if="tempOperate == 'new'" span="4" @click="showPicker('peer', 'peer', -1)">
          <div class="people-with-name">
            <van-image :src="require('../../assets/cars/add_img.png')"></van-image>
          </div>
        </van-col>
      </van-row>

      <van-cell class="required" @click="showPicker('picker', 'is_limit', -1)" title="是否另配驾驶员" :value="form.is_limit == 2 ? '是' : '否'" is-link/>

      <van-cell-group v-for="(item, index) in form.car_driver" :key="`${index}驾驶员组`" class="gray-title" :title="`车辆与驾驶员${ index + 1 }`">
        <p class="delete-car" v-if="form.car_driver.length != 1 && tempOperate == 'new'" @click="deleteCar(index)">删除</p>
        <van-cell
          class="required"
          @click="showPicker('picker', 'car', index)
          "title="车辆"
          :value="item.license_num ? `${item.license_num} - ${item.vehicle_type}` : ''"
          is-link/>
        <van-cell
          @click="showPicker('picker', 'driver', index)"
          class="sticky-cell required"
          title="驾驶员"
          :value="item.name"
          is-link/>
      </van-cell-group>
      <van-button class="add-button" v-if="form.is_limit == 2 && tempOperate == 'new'" type="default" plain block @click="addCar" icon="plus">增加车辆和驾驶员</van-button>

      <van-cell class="wrap-cell required" title="派车说明">
      </van-cell>
      <van-field type="textarea" class="input-field" v-model="form.note" placeholder="请输入"></van-field>
      <div class="bottom-button">
        <van-button @click="submitData" size="large" type="info">提交</van-button>
      </div>
      
    </van-cell-group>

    <van-popup :class="{'popup-box': tempType == 'peer' || tempType == 'user_car' || tempField == 'car' || tempField == 'driver'}" v-model="popUpShow" position="bottom" :close-on-click-overlay="tempType == 'user_car'">
      <div v-if="tempType == 'peer' || tempField == 'car' || tempField == 'driver'" class="tool-wrap">
        <span @click="onPopUpCancel">取消</span>
        <span  class="active" @click="onPopUpConfirm">确定</span>
      </div>
      <div v-if="tempType == 'user_car'" class="tool-wrap">
        <span>请选择人员</span>
      </div>
      <div v-if="tempType == 'picker'" action="/">
        <van-search
          v-if="tempField != 'is_limit'"
          v-model="searchValue"
          placeholder="请输入搜索关键词"
          show-action>
          <div slot="action" @click="onSearch">搜索</div>
        </van-search>
        <van-picker
          v-if="tempType == 'picker'"
          ref="picker"
          :swipe-duration="300"
          :value-key="returnLabel()"
          :columns="tempOptions"
          :show-toolbar="tempField == 'is_limit'"
          @cancel="onPopUpCancel"
          @confirm="onPopUpConfirm"
        />
      </div>
      <van-datetime-picker
        v-else-if="tempType == 'date' && popUpShow"
        ref="datepicker"
        v-model="tempDate"
        :swipe-duration="300"
        type="datetime"
        @cancel="onPopUpCancel"
        @confirm="onPopUpConfirm"
        :filter="filter"
      />
      <side-choose
        v-if="tempType === 'peer' && popUpShow"
        ref="sideChoose"
        :isJSON="true"
        :items.sync="departmentTree"
        :default.sync="form.peer"
        maxHeight="50vh">
      </side-choose>
      <van-tree-select
        v-if="tempType == 'user_car' && popUpShow"
        :items="departmentTree"
        :active-id.sync="form.user_car"
        :main-active-index.sync="activeIndex"
        height="50vh">
        <template #content>
          <div v-if="departmentTree[activeIndex]">
            <p v-for="choose in departmentTree[activeIndex].children" :key="`${choose.id}单选人`" class="choose-item" @click="chooseOnePeople(choose)">{{ choose.name }}</p>
          </div>
          <p v-if="departmentTree[activeIndex] && departmentTree[activeIndex].children.length == 0" class="no-data-in-tree"> 暂无人员</p>
        </template>
      </van-tree-select>
    </van-popup>

    <van-popup class="popup-box" v-model="popUpLinkShow" position="bottom" :close-on-click-overlay="false">
      <div class="tool-wrap">
        <span @click="onPopUpCancel">取消</span>
        <span class="active" @click="onPopUpConfirm">确定</span>
      </div>
      <div class="popup-body">
        <van-radio-group v-if="options.links.length > 0" v-model="tempChoosedLink">
          <van-radio v-for="(link, index) in options.links" :key="`${index}关联表`" :name="link">
            <div class="radio-item">
              <h5>{{ link.title }}</h5>
              <p><small><span class="gray-text">用车人: </span>{{ link.name }}</small></p>
              <p><small><span class="gray-text">用车时间: </span>{{ $common.convertDate(link.start_time) }} - {{ $common.convertDate(link.end_time) }}</small></p>
            </div>
          </van-radio>
        </van-radio-group>
      </div>
    </van-popup>
  </div>
</template>

<script type="text/javascript">
  import sideChoose from '../../components/SideChoose.vue'
  export default {
    components: {
      'side-choose': sideChoose
    },
    data() {
      return {
        departmentTree: [], // 人员得树形结构数据

        popUpShow: false,
        popUpLinkShow: false,

        activeIndex: 0, // 当前treeSelect的打开index
        minDate: new Date('1900-01-01 00:00:00'),
        maxDate: new Date('2100-01-01 00:00:00'),
        searchValue: '', // picker的搜索框值

        tempOperate: 'new', // 当前是新增new 进行中going (going仅能编辑: 同行人, 是否另配司机, 车辆&驾驶员) 已取消canel (cancel 仅能编辑 说明)
        tempType: 'picker', // 根据当前的类型打开不同的选择内容
        tempField: 'is_limit', // 当前操作的内容键值, 可能和tempType相同
        tempOptions: [], // 当前picker内的选项
        tempIndex: -1, // 当前操作的 车辆&驾驶员组 的索引
        tempDate: new Date(), // 当前时间的选中值 开始和结束都使用此变量, 默认是当前时间
        tempChoosed: [], // 当前选中的人员(多选)
        tempChoosedSingle: {}, // 当前选中的人员(单选)
        tempChoosedLink: {}, // 当前选中的关联审批流程 一旦选中 无法清空

        lastPeople: {uid: '', name: ''}, // 上一次的被选中人 用于在切换用车人时 过滤已经填写好的驾驶员

        options: { // picker的备选项
          is_limit: [], // 是否需要另配驾驶员
          cars: [], // 当前可选的车辆
          drivers: [], // 当前可选的驾驶员
          links: [] // 当前可选的关联表
        },
        form: {
          workid: 0, // 关联流程workid (没有关联为0
          title: '', // 关联流程标题
          user_car: '', // 用车人的名字
          uid: '', // 用车人的id
          arrange_start: '', // 时间需要处理精度 组件需要13位 保存和获取为10位
          arrange_end: '',
          destination: '',
          ex_km: '',
          peer: [],
          is_limit: 1,
          car_driver: [{car: '', driver: '', license_num: '', name: '', vehicle_type: ''}],
          note: ''
        } 
      }
    },
    watch: {
      'form.is_limit': {
        handler(newV, oldV) {
          if(newV == 1) { // 默认值为 否, 清空选择 且自动填充本人为驾驶员
            this.form.car_driver = [{car: '', driver: this.form.uid, name: this.form.user_car, vehicle_type: '' }]
          } else { // 当从否变为是时 并显示+增加按钮
            
          }
        },
      },
      'searchValue': {
        handler(newV, oldV) {
          if(newV == '') { // 被关键字清空 还原列表项
            this.getPickerOptions()
          }
        },
        deep: true
      },
    },
    mounted() {
      window.f = this
      this.getDepartment('departmentTree')
    },
    activated() {
      if(this.$route.query.id) {
        this.getEditData() // 查询详情数据（编辑回显数据）
      }
      if(this.$route.query.type != 'new') {
        this.$bridge.callHandler('navTitle', {title: '编辑派车'})
      } else {
        this.$bridge.callHandler('navTitle', {title: '新增派车'})
        this.form = {
          workid: 0, // 关联流程workid (没有关联为0
          title: '', // 关联流程标题
          user_car: '', // 用车人的名字
          uid: '', // 用车人的id
          arrange_start: '', // 时间需要处理精度 组件需要13位 保存和获取为10位
          arrange_end: '',
          destination: '',
          ex_km: '',
          peer: [],
          is_limit: 1,
          car_driver: [{car: '', driver: '', license_num: '', name: '', vehicle_type: ''}],
          note: ''
        } 
      }
      // 重新注册返回(历史回滚)
      this.$bridge.callHandler('navBack')
      this.$bridge.registerHandler('navBackClicked', _ => {
        this.$router.go(-1)
      })
      this.tempOperate = this.$route.query.type 
    },
    watch: {
      'popUpShow': {
        handler(newV, oldV) {
          if (this.popUpShow) {
            this.$bridge.callHandler('navKeepView')
          } else {
            this.$bridge.callHandler('cancelNavKeepView')
          }
        }
      },
      'popUpLinkShow': {
        handler(newV, oldV) {
          if (this.popUpLinkShow) {
            this.$bridge.callHandler('navKeepView')
          } else {
            this.$bridge.callHandler('cancelNavKeepView')
          }
        }
      }
    },
    methods: {
      /**
       * 获取备选项数据
       * @param  {String} type   根据类型获取备选项数据(人员/部门), 两种有不同的数据结构
       * @param  {String} target 数据目标key
       */
      getDepartment(target) {
        let self = this
        self.$axios.post(`${self.$common.basePath}meeting.php`, {
          do: 'department'
        }).then(res => {
          self[target] = res.data
          // 处理树形数据
          let treeData = self.$common.deepCopy(res.data)
          for (var i = 0; i < treeData.length; i++) {
            treeData[i].text = treeData[i].name
            for (var j = 0; j < treeData[i].children.length; j++) {
              (treeData[i].children)[j].text = (treeData[i].children)[j].name;
              (treeData[i].children)[j].choosed = false
            }
          }
          self[target] = treeData
        }).catch(err => { self.$toast('获取数据错误 相关功能无法使用')})
      },
      getEditData() {
        let self = this
        self.$toast({
          duration: 99999,
          forbidClick: true,
          icon: require('../../assets/loading.gif'),
        })
        self.$axios.get(`${self.$common.basePath}aatp5/public/index.php/message/api_car/messageDetail`,
        {
          params: {
            uid: self.$store.state.userId,
            id: self.$route.query.id
          }
        }).then(res => {
          res.data.arrange_start = res.data.arrange_start*1000
          res.data.arrange_end = res.data.arrange_end*1000
          self.form = res.data
          self.$toast.clear()
        }).catch(err => { self.$toast('获取数据失败')})
      },
      /**
       * 点击选择一位用车人 
       * 如果当前服务另配驾驶员 则修改当前的驾驶员为用车人
       * 如果当前用车人有默认值被填写 则需要将其清楚
       * @param  {[type]} choose [description]
       * @return {[type]}        [description]
       */
      chooseOnePeople(choose) {
        this.form.uid = choose.id
        this.form.user_car = choose.name
        if(this.form.is_limit == 1) { // 选择了否
          this.form.car_driver[0].driver = choose.id
          this.form.car_driver[0].name = choose.name
        } else { // 选择了是 前一个人已经在备选项中 需要将其清空
          this.form.car_driver.forEach(item => {
            if(this.lastPeople.id == item.id) {
              item.driver = ''
              item.name = ''
              this.$toast({ message: '用车人已修改, 已选择的驾驶员信息已被清空', duration: 3000 })
            }
          })
        }
        this.popUpShow = false
      },
      /**
       * 初始化弹窗的内容 并按需进行选中
       * @param  {[type]} type        [description]
       * @param  {[type]} dataField   [description]
       * @param  {[type]} index       [description]
       * @return {[type]}             [description]
       */
      showPicker(type, dataField, index) {
        let self = this
        // 注册所有的暂存字段用于picker选中
        self.tempType = type
        self.tempField = dataField
        this.tempIndex = index

        switch(self.tempType) {
          case 'picker':
            if(self.tempOperate != 'new') {
              self.$toast('当前状态无法修改本内容')
              return false
            }
            if (dataField == 'is_limit') { // 选择是否另配驾驶员
              self.tempOptions = [
                { label: '是', value: 2 },
                { label: '否', value: 1 }
              ]
              self.popUpShow = true
              self.$nextTick(_ => { // 设置初始选中
                let index = self.tempOptions.findIndex(item => {
                  return self.form.is_limit == item.value
                })
                self.$refs.picker.setIndexes([index])
              })
            } else { // 选择驾驶员/车辆
              if(!self.form.uid) {
                self.$toast('请先选择一位用车人')
                return false
              }
              if(self.tempField == 'driver' && self.form.is_limit == 1) {
                self.$toast('请选择 "是否另配驾驶员" 为 "是"')
                return false
              }
              // 当前有被选中的用车人 则记录为lastPeople
              if(!!self.uid) {
                this.lastPeople.id = self.uid
                this.lastPeople.name = self.user_car
              }
              self.getPickerOptions() // 根据类型获取不同的备选项
            }
            break;
          case 'date':
            if(self.tempOperate == 'cancel') {
              self.$toast('当前状态无法修改本内容')
              return false
            }
            self.tempDate = this.form[dataField] ? new Date(this.form[dataField]) : new Date()
            self.popUpShow = true
            break;
          case 'peer':
            self.popUpShow = true
            break;
          case 'user_car':
            if(self.tempOperate != 'new') {
              self.$toast('当前状态无法修改本内容')
              return false
            }
            self.popUpShow = true
            break;
          default:
            this.$toast('当前状态没有可用备选项!')
            return false
            break;
        }
      },
      /**
       * 根据类型获取 车辆/驾驶员 的备选值, 需要筛选当前已被选过的内容(当前用车人也需要按需添加至备选项中)
       * @return {[type]} [description]
       */
      getPickerOptions() {
        let self = this
        self.$toast({
          duration: 99999,
          forbidClick: true,
          icon: require('../../assets/loading.gif'),
        })
        let url = 'aatp5/public/index.php/message/api_car/'
        this.tempField == 'car' ? url += 'addCarWorkList' : url += 'addCarWorkListDriver'
        // 获取当前需要过滤的ids数组
        let arry = this.form.car_driver.map(item => { 
          if(this.tempField == 'car') {
            return item.car
          } else {
            return item.driver
          }
        })
        arry.splice(this.tempIndex, 1)
        self.$axios.get(`${self.$common.basePath}${url}`,
        {
          params: {
            uid: self.$store.state.userId,
            arrange_start: self.form.arrange_start/1000,
            arrange_end: self.form.arrange_end/1000,
            ids:  arry.join(','),
            id: self.form.uid // 携带用车人的信息 以出现在备选项中
          }
        }).then(res => {
          self.tempOptions = res.data
          // 创建一个用于显示车型和车牌的字段
          if(this.tempField == 'car') {
            self.tempOptions.forEach(item => {
              item.car_info = item.license_num + ' - ' + item.vehicle_type
            })
          }
          if (self.tempOptions && self.tempOptions.length > 0) {
            self.popUpShow = true
            self.$nextTick(_ => {// 进行默认值还原car/driver 写在同一个地方进行处理
              const index = self.tempOptions.findIndex(item => {
                return item.license_num.toUpperCase() == self.form.car_driver[self.tempIndex].license_num.toUpperCase() || item.name.toUpperCase() == self.form.car_driver[self.tempIndex].name.toUpperCase()
              })
              self.$refs.picker.setIndexes([index])
            })
            self.$toast.clear()
          } else {
            self.$toast({ message: '暂无可用数据', icon: 'fail' })
          }
        }).catch(err => { self.$toast({ message: err.msg, icon: 'cross' }) })
      },
      /**
       * 单独的弹窗用于区分 选择关联表单的内容
       * @return {[type]} [description]
       */
      showPopUpLink() {
        this.tempType = 'link'
        this.tempField = 'link'
        this.getLinks()
      },
      /**
       * 获取关联的流程表单列表
       * @return {[type]} [description]
       */
      getLinks() {
        this.$toast({
          duration: 99999,
          forbidClick: true,
          icon: require('../../assets/loading.gif'),
        })
        this.$axios.get(`${this.$common.basePath}aatp5/public/index.php/message/api_car/carWorkClass`, { params :{
            uid: this.$store.state.userId,
          }
        }).then(res => {
          if (res.data && res.data.length > 0) {
            this.options.links = res.data
            // 默认选中值
            this.options.links.forEach(item => {
              if (item.workid == this.form.workid) {
                this.tempChoosedLink = item
              }
            })
            this.popUpLinkShow = true
            this.$toast.clear()
          } else {
            this.$toast({ message: '暂无可用数据', icon: 'fail' })
          }
        }).catch(err => { this.$toast({ message: err.msg, icon: 'cross' }) })
      },
      /**
       * 根据id 获取关联表单的详情， 并填入相关数据
       * @return {[type]} [description]
       */
      getLinkDetail(id) {
        this.$toast({
          duration: 99999,
          forbidClick: true,
          icon: require('../../assets/loading.gif'),
        })
        this.$axios.get(`${this.$common.basePath}aatp5/public/index.php/message/api_car/detailCarWork`, 
        { 
          params: {
            uid: this.$store.state.userId,
            workid: id
          }
        }).then(res => {
          this.form.workid = id
          this.form.title = res.data.title
          this.form.user_car = res.data.user_car
          this.form.uid = res.data.uid
          this.form.destination = res.data.destination
          this.form.ex_km = res.data.ex_km
          this.form.arrange_start = res.data.start_car_time*1000
          this.form.arrange_end = res.data.end_car_time*1000
          this.form.peer = res.data.peer
          if(this.form.is_limit == 1) { // 填充数据后 若当前无需另配驾驶员 填充当前人
            this.form.car_driver[0].driver = res.data.uid
            this.form.car_driver[0].name = res.data.user_car
          }
          // 重新关联流程 人员变化 且选择了 '是' 根据lastPeople的值重置驾驶员
          if(this.form.is_limit == 2) {
            this.form.car_driver.forEach(item => {
              if(this.lastPeople.id == item.id) {
                item.driver = ''
                item.name = ''
              }
            })
          }
          this.popUpLinkShow = false
          this.$toast.clear()
        }).catch(err => { this.$toast({ message: err.msg, icon: 'cross' }) })
      },
      /**
       * 取消关联 只清空关联 保留数据
       * @return {[type]} [description]
       */
      cancelLink() {
        this.$bridge.callHandler('navKeepView')
        this.$dialog.confirm({
          title: '确认取消关联',
          message: '当前操作只取消关联 , 已填写的数据不会清空'
        }).then(res => {
          this.$bridge.callHandler('cancelNavKeepView')
          this.form.workid = 0
          this.form.title = ''
        }).catch(err => {
          this.$bridge.callHandler('cancelNavKeepView')
        })
      },
      /**
       * 添加一条空的 车辆/驾驶员 数据
       */
      addCar() {
        this.form.car_driver.push({car: '', driver: '', license_num: '', name: '', vehicle_type: ''})
      },
      deleteCar(index) {
        this.form.car_driver.splice(index, 1)
      },
      /**
       * 点击取消（弹窗关闭） 清空相应数据
       * @return {[type]} [description]
       */
      onPopUpCancel() {
        if(this.tempType != 'link') {
          this.popUpShow = false
        } else {
          this.tempChoosedLink = {} // 清空
          this.tempChoosedSingle = {}
          this.popUpLinkShow = false
        }
      },
      /**
       * 点击确定（弹窗关闭）填充数据至 form 内， link时需要填充更多的数据
       * @return {[type]} [description]
       */
      onPopUpConfirm(e) {
        switch(this.tempType) {
          case 'picker':
            // 正在选择 车辆/驾驶员
            if(this.tempField == 'driver'){ // 选择驾驶员
              this.form.car_driver[this.tempIndex].name = this.$refs.picker.getValues()[0].name
              this.form.car_driver[this.tempIndex].driver = this.$refs.picker.getValues()[0].uid
              this.popUpShow = false
            } else if (this.tempField == 'car') { // 选择车辆
              this.form.car_driver[this.tempIndex].license_num = this.$refs.picker.getValues()[0].license_num
              this.form.car_driver[this.tempIndex].vehicle_type = this.$refs.picker.getValues()[0].vehicle_type
              this.form.car_driver[this.tempIndex].car = this.$refs.picker.getValues()[0].vehicle_id
              this.popUpShow = false
            } else {
              if(e.value == 1) {
                this.$dialog.confirm({
                  title: '提示',
                  message: '您选择了"无需另配驾驶员", 此操作将还原当前已选择的车辆与驾驶员信息'
                }).then(() => {
                  this.form[this.tempField] = e.value
                  this.popUpShow = false
                }).catch(() => {
                });
              } else {
                this.form[this.tempField] = e.value
                this.popUpShow = false
              }
            }
            break;
          case 'date':
            this.form[this.tempField] = new Date(e).getTime()
            this.popUpShow = false
            break;
          case 'peer':
            this.form.peer = this.$refs.sideChoose.getChoosedByName();
            this.popUpShow = false
            break;
          case 'link':
            this.$dialog.confirm({
              title: '确认以当前表单自动填写',
              message: '* 如果您需要另配驾驶员且用车人被修改, 已填写的驾驶员将被清空'
            }).then(() => {
              this.getLinkDetail(this.tempChoosedLink.workid)
            }).catch(() => { });
            break;
          default:
            this.popUpShow = false
            this.$toast('当前状态无法写入值!')
            return false
            break;
        }
      },
      submitData() {
        let formData = this.$common.deepCopy(this.form)

        if(!formData.user_car || !formData.uid) {
          this.$toast({icon: 'cross', message: '用车人不能为空'})
          return false
        }
        if(!formData.arrange_start) {
          this.$toast({icon: 'cross', message: '开始时间不能为空'})
          return false
        }
        if(!formData.arrange_end) {
          this.$toast({icon: 'cross', message: '结束时间不能为空'})
          return false
        }
        if(formData.arrange_start > formData.arrange_end) {
          this.$toast({icon: 'cross', message: '开始时间不可大于结束时间'})
          return false
        }
        if(!formData.destination) {
          this.$toast({icon: 'cross', message: '目的地不能为空'})
          return false
        }
        if(!formData.note) {
          this.$toast({icon: 'cross', message: '派车说明不能为空'})
          return false
        }
        
        let flag = true
        formData.car_driver.forEach(item => {
          if(item.car == '' || item.driver == '') {
            flag = false
          }
        })
        if(!flag) {
          this.$toast({icon: 'cross', message: '车辆与驾驶员信息填写不完整'})
          return false
        }
        this.$toast({
          duration: 99999,
          forbidClick: true,
          icon: require('../../assets/loading.gif'),
        })
        formData.arrange_start = formData.arrange_start/1000
        formData.arrange_end = formData.arrange_end/1000

        formData.peer = formData.peer.map(item => { return item.id }).join(',')
        formData.car_driver = formData.car_driver.map(item => { return { car: item.car, driver: item.driver }})
        delete formData.title

        this.$axios.post(`${this.$common.basePath}aatp5/public/index.php/message/api_car/${this.tempOperate == 'new' ? 'addCarWork' : 'editorCarWork' }`, formData).then(res => {
          // 添加成功 回到上一页
          this.$toast({icon: 'success', message: '成功'})
          setTimeout(_ => {
            this.$router.go(-1)
          }, 500)
          
        }).catch(err => { this.$toast({icon: 'cross', message: err.msg }) })
      },
      /**
       * 根据当前的tempField决定value-key的值
       * @return {[type]} [description]
       */
      returnLabel() {
        switch(this.tempField) {
          case 'is_limit':
          default:
            return 'label'
            break;
          case 'car':
            return 'car_info'
            break;
          case 'driver':
            return 'name'
            break;
        }
      },
      /**
       * 点击搜索 过滤选项 存放至resultField
       * @param  {Array} tempPopupField 当前的列表源数据(过滤前)
       */
      onSearch() {
        let self = this
        let result = self.tempOptions.filter(item => {
          return item.car_info.indexOf(this.searchValue) != -1 || item.vehicle_type.indexOf(this.searchValue) != -1
        })
        this.tempOptions = result
      },
      filter(type, options) {
        if (type === 'minute') {
          return options.filter(option => option <= 0);
        }
        return options;
      }
    }
  }
</script>

<style lang="less" scoped>
  #carform {
    background: #f5f5f5;
    min-height: 100vh;
    & /deep/ .van-picker__cancel {
      color: #333;
    }
    .required:before {
      content: '*';
      color: red;
    }
    .active {
      color: #2E79FF;
    }
    .no-data-in-tree {
      margin: 15px;
      color: #999;
      text-align: center;
    }
    .popup-box {
      padding-top: 51px;
      .tool-wrap {
        position: absolute;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px;
        top: 0;
        width: calc( 100vw - 30px );
        color: #333;
        z-index: 999;
      }
      .popup-body {
        overflow-y: auto;
        padding: 5px 15px 0 15px;
        max-height: 80vh;
        .van-radio {
          margin-bottom: 15px;
          align-items: flex-start;
        }
        .radio-item {
          h5, p {
            margin: 0;
          }
          h5 {
            font-size: 17px;
            color: #333;
            font-weight: normal;
          }
          .gray-text {
            color: #999;
          }
          p small {
            font-size: 12px;
          }
        }
      }
      
      & /deep/ .title {
        padding-right: 15px!important;
      }
      & /deep/ .van-tree-select__item--active {
        color: #2E79FF;
      }
      & /deep/ .van-sidebar-item--select {
        border-color: #2E79FF;
      }
      & /deep/ .choose-item {
        padding: 10px 15px;
        margin: 0;
      }
    }

    .top-area {
      display: flex;
      justify-content: center;
      .top-button {
        font-size: 17px;
        margin-top: 15px;
        margin-bottom: 5px;
        border: 1px dashed #2E79FF;
        background: #f5f5f5;
      }
    }
    
    .peoples {
      margin: 0!important;
      width: calc( 100vw - 30px );
      background: #fff;
      padding: 0 15px;
      .people-with-name {
        width: 100%;
        margin-bottom: 10px;
        .van-image {
          display: block;
          margin: auto;
          width: calc( 100vw / 6 - 18px);
          height: calc( 100vw / 6 - 18px);
          border-radius: 8px;
          overflow: hidden;
        }
        p {
          padding-top: 4px;
          margin: 0;
          font-size: 12px;
          text-align: center;
        }
      }
    }
    .bottom-button {
      margin-top: 10px;
      padding: 5px 10px;
      background-color: #fff;
    }
  }
  .delete-car {
    position: absolute;
    right: 15px;
    top: -45px;
    color: #2E79FF;
  }
  & /deep/ .add-button {
    border: none;
    box-shadow: none;
    color: #2E79FF!important;
  }
  .van-cell-group__title {
    background: #f5f5f5;
  }
  .van-cell-group {
    background: #f5f5f5;
    & /deep/ .van-cell {
      margin-top: 10px;
      align-items: center;
      &.sticky-cell {
        margin-top: 0;
      }
      &.wrap-cell {
        padding-bottom: 0;
        &:after {
          border-bottom: 0;
        }
      }
      
    }
    .input-field {
      display: block;
      padding-top: 0;
      margin-top: 0;
    }
    .van-cell .input-field-inline {
      margin: 0;
      padding: 0;
      & /deep/ .van-field__control {
        text-align: right!important;
      }
    }
  }
</style>